﻿using CurrentUserDemo.Api.Infrastructures.Claims;
using DotNetCore.CAP;
using DotNetCore.CAP.Filter;
using System.Security.Claims;

namespace CurrentUserDemo.Api.Infrastructures.Filters;

public class MyCapFilter : SubscribeFilter
{
    private readonly ICurrentPrincipalAccessor _currentPrincipalAccessor;
    private IDisposable currentPrincipalAccessorDisposable;

    public MyCapFilter(ICurrentPrincipalAccessor currentPrincipalAccessor)
    {
        _currentPrincipalAccessor = currentPrincipalAccessor;
    }

    public override Task OnSubscribeExecutingAsync(ExecutingContext context)
    {
        Console.WriteLine("message time is:" + context.Arguments.First());

        var header = (context.Arguments.Last() as CapHeader)!;
        Console.WriteLine("message firset header :" + header["my.header.first"]);
        Console.WriteLine("message second header :" + header["my.header.second"]);
        Console.WriteLine("message uid header :" + header["my.header.uid"]);
        currentPrincipalAccessorDisposable = _currentPrincipalAccessor.Change(new Claim("uid", header["my.header.uid"] + "1"));
        return Task.CompletedTask;
    }

    public override Task OnSubscribeExecutedAsync(ExecutedContext context)
    {
        currentPrincipalAccessorDisposable.Dispose();
        return Task.CompletedTask;
    }

    public override Task OnSubscribeExceptionAsync(ExceptionContext context)
    {
        currentPrincipalAccessorDisposable.Dispose();
        return Task.CompletedTask;
    }
}